// pages/userCenter/jiedan/jiedan.js
const regex = require('../../../utils/regex')
const request = require('../../../utils/request')
const utils = require('../../../utils/util')
Page({
  data: {
    carInfo: {
      type: '',
      owner: '',
      ownerPhone: '',
      sender: '',
      senderPhone: ''
    },
    submitData: {},
    info: {
      chepai: '',
      danhao: '',
      cometime: '',
      licheng: '',
      xinagmu: '',
      waiguan: '',
      jiancha: '',
      weixiuxiang: '',
      peijianxiang: ''
    },
    id: '',
    total_price_dialog: false,

    returnOrder: '',
    type: '',
    inputFocus: false
  },
  touchHandler:function() {
    return;
  },
  tapInput() {
    this.setData({
      //在真机上将焦点给input
      inputFocus: true,
      //初始占位清空
      inputInfo: ''
    });
  },
  onLoad: function (options) {
    request.get('create_order_no')
      .then(res => {
        this.setData({
          ["info.danhao"]: res.data
        })
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {

      })


    this.setData({
      ["info.cometime"]: this.getNowTime(),
      type: options.type ? options.type : "",
      id: options.id ? options.id : "",
      isStaff: utils.isStaff()
    })
    if (options.id) {
      this.getDetail(options.id)
    } 
  },
  onReady() {
    switch (this.data.type) {
      case 'jiechedan':
        this.setNavigationBarTitle('维修单')
        break
      case 'guazhangdan':
        this.setNavigationBarTitle('挂帐单')
        break
      case 'jiesuandan':
        this.setNavigationBarTitle('结算单')
        break  
      default:
        this.setNavigationBarTitle('接单')
        break
    }
  },
  setNavigationBarTitle(title) {
    wx.setNavigationBarTitle({ title })
  },
  getDetail(id) {
    wx.showLoading()
    request.get('repair_detail', { id })
      .then(res => {
        wx.hideLoading()
        if (res.data) {
          const data = res.data;
          console.log(data)
          this.setData({
            info: {
              chepai: data.chepai,
              danhao: data.danhao,
              cometime: data.sj,
              licheng: data.licheng,
              xiangmu: data.xiangmu,
              waiguan: data.waiguan,
              jiancha: data.free_jiance,
              weixiuxiang: data.weixiuxiang,
              peijianxiang: data.peijianxiang,
            },
            carInfo: {
              type: data.chexing,
              owner: data.chezhu,
              ownerPhone: data.dianhua,
              sender: data.songxiuren,
              senderPhone: data.sxrdh
            },
          })
          this.setData({
            returnOrder: data,
          })
        }
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },

  getNowTime() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = String(month).length <= 1 ? '0' + String(month) : month;
    let day = date.getDate()
    day = String(day).length <= 1 ? '0' + String(day) : day;
    let hour = date.getHours()
    hour = String(hour).length <= 1 ? '0' + String(hour) : hour;
    let minute = date.getMinutes()
    minute = String(minute).length <= 1 ? '0' + String(minute) : minute;
    let second = date.getSeconds()
    second = String(second).length <= 1 ? '0' + String(second) : second;
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  },

  inputchepai(e) {
    this.setData({
      ["info.chepai"]: e.detail.value
    });
  },
  searchHistory() {
    wx.showLoading()
    request.get('decide_chepai', { code: this.data.info.chepai })
      .then(res => {
        wx.hideLoading()
        if (res.data) {
          const data = res.data
          this.setData({
            carInfo: {
              type: data.chexing,
              owner: data.chezhu,
              ownerPhone: data.dianhua,
              sender: data.songxiuren,
              senderPhone: data.sxrdh
            }
          })
          return
        }
        wx.showToast({
          icon: 'none',
          title: '未搜索到相关车辆'
        })
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },

  changePrice(e) {
    const type = e.target.dataset.type
    const totalPrice = "returnOrder.total_price"
    this.setData({
      [totalPrice]: type == 'value' ? e.detail.value : e.detail
    });
  },
  dialogHide() {
    this.setData({
      total_price_dialog: false
    })
  },
  editPrice() {
    this.setData({
      total_price_dialog: false
    })
    wx.hideLoading()
    const returnOrder = this.data.returnOrder;

    request.post('price_edit', {id: returnOrder.id, total_price: returnOrder.total_price, danhao: returnOrder.danhao})
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '修改成功'
        })
        var _this = this
        setTimeout(() => {
          if (this.data.type && this.data.type != '') {
            var pages = getCurrentPages();
            if (pages.length > 1) {
              var beforePage = pages[pages.length - 2]
              beforePage.setData({
                type: this.data.type,
                page: 0,
                repairList: []
              })
              beforePage.refreshData();
            }
            wx.navigateBack({delta:1})
          } else {
            wx.redirectTo({
              url: '../../index/weixiuHome/jiechedan/jiechedan?type=jiechedan'
            })
          }
        }, 1000)
        
      })
      .catch(error => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
  hiddenModal() {
    this.setData({ total_price_dialog: false })
  },
  formSubmit(e) {
    const value = e.detail.value
    if (!value.chepai) {
      wx.showToast({
        icon: 'none',
        title: '请填写车牌'
      })
      return
    }

    if (!value.danhao) {
      wx.showToast({
        icon: 'none',
        title: '请填写单号'
      })
      return
    }
    
    if (!value.chexing) {
      wx.showToast({
        icon: 'none',
        title: '请填写车型'
      })
      return
    } 

    if (!value.chezhu) {
      wx.showToast({
        icon: 'none',
        title: '请填写车主'
      })
      return
    }

    if (!value.dianhua) {
      wx.showToast({
        icon: 'none',
        title: '请填写车主联系电话'
      })
      return
    }

    if (!regex.phone.test(value.dianhua)) {
      wx.showToast({
        icon: 'none',
        title: '车主联系电话格式不正确'
      })
      return
    }

    if (!value.songxiuren) {
      wx.showToast({
        icon: 'none',
        title: '请填写送修人'
      })
      return
    }

    if (!value.sxrdh) {
      wx.showToast({
        icon: 'none',
        title: '请填写送修人电话'
      })
      return
    }

    if (!regex.phone.test(value.sxrdh)) {
      wx.showToast({
        icon: 'none',
        title: '送修人联系电话格式不正确'
      })
      return
    }

    if (!value.licheng) {
      wx.showToast({
        icon: 'none',
        title: '请填写里程'
      })
      return
    }

    const data = {
      chepai: value.chepai,
      danhao: value.danhao,
      chexing: value.chexing,
      chezhu: value.chezhu,
      dianhua: value.dianhua,
      songxiuren: value.songxiuren,
      sxrdh: value.sxrdh,
      licheng: value.licheng,
      xiangmu: value.xiangmu,
      waiguan: value.waiguan,
      free_jiance: value.jiancha,
      weixiuxiang: value.weixiuxiang,
      peijianxiang: value.peijianxiang,
    }
    this.setData({
      'info.xiangmu': value.xiangmu,
      'info.waiguan': value.waiguan ? value.waiguan : '',
      'info.jiancha': value.jiancha,
      'info.weixiuxiang': value.weixiuxiang,
      'info.peijianxiang': value.peijianxiang,
    })

    wx.showLoading()
    var url;
    if (this.data.type && this.data.type != '') {
      url = 'repair_edit'
    } else {
      url = 'jd_repair'
    }
    request.get(url, data)
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: res.msg
        })
        console.log(this.data.info)
        console.log(this.data.submitData)
        if (res.data[0]) {
          this.setData({
            returnOrder: res.data[0],
          })
        }
        console.log(this.data.info)
        console.log(this.data.submitData)
        // if (!this.data.type) {
          setTimeout(() => {
            this.setData({ total_price_dialog: true })
          }, 1000)
        // } else {
        //   this.editPrice();
        // }
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
  settleBill() {
    wx.showLoading()
    request.post('sc_guazhang', { id: this.data.id })
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: res.msg
        })
        setTimeout(() => {
          var pages = getCurrentPages();
          if (pages.length > 1) {
            var beforePage = pages[pages.length - 2]
            beforePage.setData({
              type: 'guazhangdan',
              page: 0,
              repairList: []
            })
            beforePage.refreshData();
          }
          wx.navigateBack({ delta: 1 })
        }, 1000)
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
  settleAccount() {
    wx.showLoading()
    request.get('jiesuan', { id: this.data.id })
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: "生成结算单成功"
        })
        setTimeout(() => {
          var pages = getCurrentPages();
          if (pages.length > 1) {
            var beforePage = pages[pages.length - 2]
            beforePage.setData({
              type: 'jiesuandan',
              page: 0,
              repairList: []
            })
            beforePage.refreshData();
          }
          wx.navigateBack({ delta: 1 })
        }, 1000)
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },
})
